package com.huluobo.a2204kotlinshopping.cart

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ApiUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2204kotlinshopping.R
import com.huluobo.a2204kotlinshopping.adapter.CartAdapter
import com.huluobo.a2204kotlinshopping.databinding.FragmentCartBinding
import com.huluobo.a2204kotlinshopping.otder.PayActivity
import com.huluobo.base.bean.CartBean
import com.huluobo.base.bean.OrderBean
import com.huluobo.base.bean.OrderType
import com.huluobo.base.bean.OrderTypeBean
import com.huluobo.base.db.AppDBUtils
import com.huluobo.base.view.BaseMVVMFragment

class CartFragment : BaseMVVMFragment<FragmentCartBinding, CartViewModel>() {
    private lateinit var cartAdapter: CartAdapter
    private val cartList = mutableListOf<CartBean>()
    override fun getLayoutId(): Int = R.layout.fragment_cart

    override fun initData() {
        viewModel.getCartList()

        viewModel.getCartListSuccess.observe(this) {
            if (it.code == 200) {
                cartList.clear()
                cartList.addAll(it.data)
                dataBinding.cartSelectAllCb.isChecked = false
                cartAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getCartListFailed.observe(this) {
            Log.i("TagA", "获取购物车数据失败:$it")
        }

        viewModel.changeCartCountSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong("修改购物车数量成功")
            } else {
                ToastUtils.showLong("修改购物车数量失败 :${it.message}")
            }
        }

        viewModel.changeCartCountFailed.observe(this) {
            Log.i("TagA", "修改购物车数量失败:$it")
        }
    }

    override fun initView() {
        dataBinding.cartRv.layoutManager = LinearLayoutManager(requireContext())
        cartAdapter = CartAdapter(cartList)
        dataBinding.cartRv.adapter = cartAdapter

        totalPrice()

        cartAdapter.addChildClickViewIds(
            R.id.item_cart_cb,
            R.id.item_cart_add_iv,
            R.id.item_cart_remove_iv,
            R.id.item_cart_delete_iv
        )

        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.item_cart_cb -> {
                    cartList[position].isChecked = !cartList[position].isChecked
                    (adapter.getViewByPosition(position, R.id.item_cart_cb) as CheckBox).isChecked =
                        cartList[position].isChecked
                    checkAll()
                }

                R.id.item_cart_add_iv -> {
                    cartList[position].count += 1
                    viewModel.changeCartCount(1, cartList[position].goods_id)
                    (adapter.getViewByPosition(position, R.id.item_cart_num_tv) as TextView).text =
                        "${cartList[position].count}"
                }

                R.id.item_cart_remove_iv -> {
                    if (cartList[position].count > 1) {
                        cartList[position].count -= 1
                        viewModel.changeCartCount(-1, cartList[position].goods_id)
                        (adapter.getViewByPosition(position, R.id.item_cart_num_tv) as TextView).text =
                            "${cartList[position].count}"
                    }
                }

                R.id.item_cart_delete_iv -> {
                    val ids = cartList[position].id.toString()
                    viewModel.deleteCart(ids)

                    cartList.removeAt(position)
                    adapter.notifyItemRemoved(position)
                }

            }

            //无论点击了item中哪一个按钮,都需要重新计算一下总价,包括选中,删除,修改数量
            totalPrice()
        }

        //全选按钮的点击事件
        dataBinding.cartSelectAllCb.setOnCheckedChangeListener { buttonView, isChecked ->
            dataBinding.cartSelectAllCb.setOnClickListener {
                cartList.forEach {
                    it.isChecked = isChecked
                }
                cartAdapter.notifyDataSetChanged()
                totalPrice()
            }
        }

        //立即支付点击事假
        dataBinding.cartPayBtn.setOnClickListener {
            val checkList = mutableListOf<Boolean>()
            //所有订单中的商品的list
            val orderList = ArrayList<OrderBean>()
            cartList.forEach {
                if (it.isChecked) {
                    checkList.add(it.isChecked)
                    //给订单集合添加一个订单的bean
                    orderList.add(
                        //如果商品是选中的状态,生成一个订单的bean
                        OrderBean(
                            it.count,
                            it.goods_default_price,
                            it.goods_desc,
                            it.id
                        )
                    )
                }
            }
            //由于数据库中无法直接保存list,所以把list转换为一个json来保存,读取的时候,需要吧json转换为list来赋值
            val orderJson = Gson().toJson(orderList)
            //当有商品被选中时,可以继续点击立即购买
            if (true in checkList) {
                //带订单类型的bean,其中包含订单类型和所有订单数据
                val orderTypeBean = OrderTypeBean(
                    orderJson,
                    OrderType.PRE_PAY
                )
                AppDBUtils.getDb().orderTypeDao.deleteAllOrder()
                //生成待付款订单
                AppDBUtils.getDb().orderTypeDao.insertOrderType(orderTypeBean)

                val intent = Intent(requireContext(), PayActivity::class.java)
                startActivity(intent)
            } else {
                ToastUtils.showLong("至少选中一件商品")
            }

        }

    }

    override fun getViewModel(): Class<CartViewModel> {
        return CartViewModel::class.java
    }

    private fun totalPrice() {
        var totalPrice = 0

        cartList.forEach {
            if (it.isChecked) {
                totalPrice += it.goods_default_price * it.count
            }
        }

        dataBinding.cartTotalPriceTv.text = "总价:￥$totalPrice"
    }

    //检查是否item中所有的数据勾选状态
    private fun checkAll() {
        val checkList = mutableListOf<Boolean>()
        cartList.forEach {
            //把购物车中所有的是否选中放到一个集合中
            checkList.add(it.isChecked)
        }
        //如果未选中存在于集合中,就设置全选按钮未选中
        dataBinding.cartSelectAllCb.isChecked = false !in checkList
    }
}